import { Service } from "egg";
import { Types } from "mongoose";
import { BusinessCompanyProps } from "../model/BusinessCompany";
import { IndexCondition } from "../common";

export default class BusinessCompanyService extends Service {
  /**
   * 根据传入名称查询
   */
  public findByName(name: string) {
    return this.ctx.model.BusinessCompany.findOne({ name });
  }

  /**
   * 查找列表
   * @param {IndexCondition} condition 查询条件
   */
  public async findList(condition: IndexCondition) {
    const { ctx } = this;
    const { select, pageSize, pageIndex, find } = condition;
    const skip = pageIndex && pageSize ? pageIndex * pageSize : 0;
    const res = await ctx.model.BusinessCompany.find(find ? find : {})
      .select(select)
      .skip(skip)
      .limit(typeof pageSize === "number" ? pageSize : 10)
      .lean();
    const count = await ctx.model.BusinessCompany.find(
      find ? find : {}
    ).count();
    return {
      count,
      list: res,
      pageSize,
      pageIndex: pageIndex !== undefined ? pageIndex + 1 : 10,
    };
  }

  /**
   * 添加数据
   * @param data 测试数据
   */
  public async add(data) {
    const { ctx } = this;
    // TODO 暂时写死公司ID，后续需要从ctx.state.user获取
    const { user: userInfo } = ctx.state;
    const _data: Partial<BusinessCompanyProps> = {
      ...data,
      company_id: Types.ObjectId(userInfo.company),
    };
    return await ctx.model.BusinessCompany.create(_data);
  }
}
